package cn.omisheep.au.core.filter;


import cn.omisheep.au.core.AuRsa;
import cn.omisheep.au.core.AuUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.*;
import java.util.stream.Collectors;

/**
 * @author zhou xin chen  😊
 * 联系方式 qq:1269670415  email:xinchenzhou666@gmail.com
 */
@Slf4j
public class AuDecryptMethodArgument implements HttpInputMessage {

    private final HttpHeaders headers;
    private final InputStream body;

    public AuDecryptMethodArgument(HttpInputMessage inputMessage, String privateKey) throws IOException {
        this.headers = inputMessage.getHeaders();
        String content = new BufferedReader(new InputStreamReader(inputMessage.getBody()))
                .lines().collect(Collectors.joining(System.lineSeparator()));
        // 将原本的json整个加密，然后再放到一个空对象中，请勿直接传递加密的数据，因为加密的数据不再是一个json对象，如果前端使用axios会类型报错
        String text = AuUtil.parse_RSA_JSON(content);
        String decrypt = AuRsa.decrypt(text, privateKey);
        this.body = new ByteArrayInputStream(decrypt.getBytes());
    }

    @Override
    public InputStream getBody() {
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }
}